package com.example.biye;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import java.util.ArrayList;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Toast;
import android.database.sqlite.SQLiteDatabase;


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.speech.tts.TextToSpeech;
import com.example.biye.permission.CustomPermissionUtil;
import com.example.biye.permission.PermissionCallback;
import com.example.biye.permission.RequestBean;
import com.example.biye.service.ImportDeviceService;

import java.util.Date;
import java.util.Locale;
import com.example.biye.util.PermissionUtil;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashMap;
import java.util.Map;
import android.media.SoundPool;
import android.media.AudioAttributes;
import android.media.AudioManager;
import com.example.biye.bean.UserInfo;
import com.example.biye.database.UserDBHelper;
import com.example.biye.util.DateUtil;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import java.util.Collection;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.example.biye.custom.MyMarkerView;
import java.util.ArrayList;
import java.util.List;
import com.github.mikephil.charting.utils.Utils;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import com.github.mikephil.charting.formatter.ValueFormatter;







public class TabSecondActivity extends AppCompatActivity {
    private TextView test_xinlv;
    private TextView test_xueyang;

    private SharedPreferences ShujuerShared;
    private SharedPreferences ShujuxianshiShared;
    private SharedPreferences.Editor editor;
    private TextToSpeech textToSpeech = null;
    private SoundPool soundPool;
    private AudioManager audioManager;
    private Map<Integer, Integer> soundmap = new HashMap<Integer, Integer>();
    private static final int MAX_STREAMS = 10;
    private static final int streamType = AudioManager.STREAM_MUSIC;
    private boolean loaded;
    private float volume;
    private int soundIdA;
    private int soundIdB;
    private int soundIdC;
    private int soundIdD;
    private int soundIdE;
    private int soundIdF;
    private TextView tv_database;
    private String mDatabaseName;
    private UserDBHelper mHelper;
    private LineChart lineChart;
    private SeekBar seekBarX, seekBarY;
    //private TextView tvX, tvY;
    private SimpleDateFormat dfs = new SimpleDateFormat("HH:mm:ss");
    private List<String> timeList = new ArrayList<>(); //存储x轴的时间
    public static final int UPDATE_TUXIANG = 1;



    String tag = "----" + TabSecondActivity.class.getSimpleName();

    static Context mAppContext;


    //要申请的权限
    final String[] permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION};


    //要申请权限的回调
    PermissionCallback callback = new PermissionCallback() {

        @Override
        public void onPermissionGranted() {
            toast("权限申请成功--方式1");
            Intent intent = new Intent(TabSecondActivity.this, BluetoothActivity.class);
            startActivityForResult(intent, 2);
            //startActivity(intent);
        }

        @Override
        public void shouldShowRational(final RequestBean requestBean, String[] rationalPermissons, final boolean before) {

            StringBuilder sb = new StringBuilder();
            sb.append("我们将获取以下权限:\n\n");

            for (int i = 0; i < rationalPermissons.length; i++) {
                sb.append((i + 1) + "、");
                /*if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(rationalPermissons[i])) {
                    sb.append("读写设备外部存储空间的权限，将被用于获取用户头像、保存一些文件到项目文件夹中");
                } else if (Manifest.permission.CAMERA.equals(rationalPermissons[i])) {
                    sb.append("使用摄像头的权限将，被用于拍照获取用户头像，直播视频采集");
                } else if (Manifest.permission.READ_PHONE_STATE.equals(rationalPermissons[i])) {
                    sb.append("读取手机状态信息的权限，将被用于登录时账号验证");
                } else if (Manifest.permission.RECORD_AUDIO.equals(rationalPermissons[i])) {
                    sb.append("录制引起的权限，将被用于直播音频采集");
                }*/
                if (Manifest.permission.ACCESS_FINE_LOCATION.equals(rationalPermissons[i])) {
                    sb.append("将要获取ACCESS_FINE_LOCATION");
                } else if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(rationalPermissons[i])) {
                    sb.append("将要获取ACCESS_COARSE_LOCATION");
                }

                if (i == rationalPermissons.length - 1) {
                    sb.append("。");
                } else {
                    sb.append("；");
                }

                sb.append("\n");
            }

            CustomPermissionUtil.showDialog(TabSecondActivity.this, sb.toString(),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //重新申请权限
                            CustomPermissionUtil.requestAgain(TabSecondActivity.this, requestBean);
                        }
                    });
        }


        @Override
        public void onPermissonReject(String[] rejectPermissons) {
            StringBuilder sb = new StringBuilder();
            sb.append("我们需要的权限:\n\n");

            for (int i = 0; i < rejectPermissons.length; i++) {
                sb.append((i + 1) + "、");
                /*if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(rejectPermissons[i])) {
                    sb.append("读写外部存储空间的权限，将被用于获取用户头像、保存一些文件到项目文件夹中");
                } else if (Manifest.permission.CAMERA.equals(rejectPermissons[i])) {
                    sb.append("使用摄像头的权限，被用于拍照获取用户头像，直播视频采集");
                } else if (Manifest.permission.READ_PHONE_STATE.equals(rejectPermissons[i])) {
                    sb.append("读取手机状态信息的权限，将被用于登录时账号验证");
                } else if (Manifest.permission.RECORD_AUDIO.equals(rejectPermissons[i])) {
                    sb.append("录制引起的权限，将被用于直播音频采集");
                }*/
                if (Manifest.permission.ACCESS_FINE_LOCATION.equals(rejectPermissons[i])) {
                    sb.append("将要获取ACCESS_FINE_LOCATION");
                } else if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(rejectPermissons[i])) {
                    sb.append("将要获取ACCESS_COARSE_LOCATION");
                }
                if (i == rejectPermissons.length - 1) {
                    sb.append("。");
                } else {
                    sb.append("；");
                }
                sb.append("\n");
            }
            sb.append("\n被设为禁止,请到设置里开启权限");

            CustomPermissionUtil.showDialog(TabSecondActivity.this, sb.toString(),
                    getString(R.string.dialog_cancel),
                    getString(R.string.dialog_go_setting),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //重新申请权限
                            CustomPermissionUtil.startSettingsActivity(TabSecondActivity.this);
                        }
                    }
            );
        }
    };
    private  Handler hander = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what) {
                case UPDATE_TUXIANG:
                    mHelper.openReadLink();
                    ArrayList<UserInfo> userArray = mHelper.query("1=1");
                    int shujugehsu = userArray.size();
                    if(shujugehsu% 10 == 0) {
                        setData(shujugehsu, 180);
                        lineChart.animateX(9000);
                    }
                    break;
                default:
                    break;

            }
        }
    };
    private  Handler xhander = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what) {
                case 1:
                    test_xinlv.setText(""+msg.arg1);
                    break;
                default:
                    break;

            }
        }
    };
    private  Handler yhander = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what) {
                case 1:
                    test_xueyang.setText(""+msg.arg1);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        // 生成一个测试数据库的完整路径
        mDatabaseName = getFilesDir() + "/test.db";
        switch (requestCode) {
            case 2:
                if (resultCode == RESULT_OK) {
                    mHelper = UserDBHelper.getInstance(this, 2);
                        MyThreadx myThreadx = new MyThreadx();
                        new Thread(myThreadx).start();
                        MyThready myThready = new MyThready();
                        new Thread(myThready).start();
                        MyThreadg myThreadg = new MyThreadg();
                        new Thread(myThreadg).start();
                }
                break;
            default:
                break;
        }
    }

    class MyThreadx implements Runnable {
        @Override
        public void run() {
            SharedPreferences jinjiShared = getSharedPreferences("share_jinji", MODE_PRIVATE);
            SharedPreferences baocunShared = getSharedPreferences("share_baocun", MODE_PRIVATE);
            //SharedPreferences ShujuxianshiShared = getSharedPreferences("share_shujuer", MODE_PRIVATE);
            String dianhua = jinjiShared.getString("jinjidianhua", "");
            String jinjixingming = jinjiShared.getString("jinjixingming", "");
            String xingming = baocunShared.getString("xingming", "");
            int gengxin = 0;
            for (int i = 0; i < 2147483647; i++) {
                mHelper.openReadLink();
                ArrayList<UserInfo> userArray = mHelper.query("1=1");
                int shujugehsu = userArray.size();
                if (shujugehsu > gengxin) {
                    UserInfo info = userArray.get(shujugehsu - 1);
                    gengxin = shujugehsu;
                    int xl = info.xinlv;
                    String returnxinlv = String.valueOf(xl);
                    //String returnxinlv = ShujuxianshiShared.getString("returnxinlv","");
                    //int xl = Integer.parseInt(returnxinlv);
                    Message xmessage = new Message();
                    xmessage.what = 1;
                    xmessage.arg1 = xl;
                    xhander.sendMessage(xmessage);
                    if (returnxinlv == null || returnxinlv.length() == 0) {
                    } else {
                        if (xl > 100 && xl < 160) {
                            playSoundA();
                            SmsManager smsManager = SmsManager.getDefault();
                            smsManager.sendTextMessage(dianhua, null, jinjixingming + "先生/女士，用户" + xingming + "将您设为紧急联系人，该用户出现窦性心动过速，不利于安全行驶，请及时联系该用户或报警。\n" + "心率为" + xl + "次/分", null, null);
                        } else if (xl >= 160 && xl <= 220) {
                            playSoundB();
                            SmsManager smsManager = SmsManager.getDefault();
                            smsManager.sendTextMessage(dianhua,null,jinjixingming+"先生/女士，用户"+xingming+"将您设为紧急联系人，该用户出现心率过高症状，不利于安全行驶，请及时联系该用户或报警。\n" +"用户心率为"+xl+"次/分钟",null,null);
                        } else if (xl < 40 && xl > 0) {
                            playSoundC();
                            SmsManager smsManager = SmsManager.getDefault();
                            smsManager.sendTextMessage(dianhua,null,jinjixingming+"先生/女士，用户"+xingming+"将您设为紧急联系人，该用户出现心率过低症状，不利于安全行驶，请及时联系该用户或报警。\n" +"用户心率为"+xl+"次/分钟",null,null);
                        }
                    }
                    delay(12000);
                }
                else{
                    break;
                }
            }
        }
    }
    class MyThready implements Runnable {
        @Override
        public void run() {
            SharedPreferences jinjiShared = getSharedPreferences("share_jinji", MODE_PRIVATE);
            SharedPreferences baocunShared = getSharedPreferences("share_baocun", MODE_PRIVATE);
            String dianhua = jinjiShared.getString("jinjidianhua", "18403009754");
            String jinjixingming = jinjiShared.getString("jinjixingming", "");
            String xingming = baocunShared.getString("xingming", "");
            int gengxin = 0;
            for (int j = 0; j < 2147483647; j++) {
                mHelper.openReadLink();
                ArrayList<UserInfo> userArray = mHelper.query("1=1");
                int shujugehsu = userArray.size();
                if (shujugehsu > gengxin) {
                    UserInfo info = userArray.get(shujugehsu - 1);
                    gengxin = shujugehsu;
                    int xy = info.xueyang;
                    String returnxueyang = String.valueOf(xy);
                    //String returnxueyang = ShujuxianshiShared.getString("returnxueyang","");
                    //int xy = Integer.parseInt(returnxueyang);
                    Message ymessage = new Message();
                    ymessage.what = 1;
                    ymessage.arg1 = xy;
                    yhander.sendMessage(ymessage);
                    if (returnxueyang == null || returnxueyang.length() == 0) {
                    } else {
                        if (xy >= 70 && xy <= 90) {
                            SmsManager smsManagerk = SmsManager.getDefault();
                            smsManagerk.sendTextMessage(dianhua, null, jinjixingming + "先生/女士，用户" + xingming + "将您设为紧急联系人，该用户出现低血氧症状，不利于安全行驶，请及时联系该用户或报警。\n" + "用户血氧为" + xy + "%", null, null);
                            delay(6000);
                            playSoundD();
                        } else if (xy > 90 && xy <= 94) {
                            delay(6000);
                            playSoundE();
                        } else if (xy <= 100 && xy > 97) {
                            delay(6000);
                            playSoundF();
                        }
                        else if(xy <= 97 && xy > 94) {
                            delay(6000);
                        }
                    }
                    delay(6000);
                }else{
                    break;
                }
            }
        }
    }

    class MyThreadg implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 2147483647; i++) {
                Message message = new Message();
                message.what = UPDATE_TUXIANG;
                hander.sendMessage(message);
                delay(3000);
            }
        }
    }

    private void setData(int count, float range) {

        // 打开数据库帮助器的读连接

        mHelper.openReadLink();
        ArrayList<UserInfo> userArray = mHelper.query("1=1");
        ArrayList<Entry> values = new ArrayList<>();
        int geshu = count;
        if (geshu % 10 == 0&&geshu>0) {
            int k = geshu / 10;
            Float[]  dianji = new Float[k];
            Float[]  xdianji = new Float[k];
            for (int j = 0; j < k; j++) {
                float zongxinlv = 0;
                for (int i = 0 + j * 10; i < 10 + j * 10; i++) {
                    UserInfo info = userArray.get(i);
                    float val = (float) (info.xinlv);
                    float shijian = info.shijian;
                    zongxinlv = val + zongxinlv;
                    if (i == 9 + j * 10) {
                        float pingjunxinlv = (float) Math.rint(zongxinlv / 10);
                        dianji[j] =  pingjunxinlv;
                        xdianji[j] =  shijian;
                    }
                }
            }
            if(geshu<=50) {
                for (int m = 0; m < k; m++) {
                    values.add(new Entry(xdianji[m], dianji[m], getResources().getDrawable(R.drawable.star)));
                }
            }
            else{
                for (int m = k-5; m < k; m++) {
                    values.add(new Entry(xdianji[m], dianji[m], getResources().getDrawable(R.drawable.star)));
                }
            }
            LineDataSet set1;
            //如果图表存在，则更新图标
            if (lineChart.getData() != null &&
                    lineChart.getData().getDataSetCount() > 0) {
                set1 = (LineDataSet) lineChart.getData().getDataSetByIndex(0);
                set1.setValues(values);
                set1.notifyDataSetChanged();
                lineChart.getData().notifyDataChanged();
                lineChart.notifyDataSetChanged();
            } else {
                // create a dataset and give it a type
                set1 = new LineDataSet(values, "心率变化曲线");
                set1.setDrawIcons(false);
                set1.enableDashedLine(10f, 5f, 0f);
                // black lines and points
                set1.setColor(Color.BLACK);
                set1.setLineWidth(1f);
                // line thickness and point size
                // 设置坐标点为实心环状
                set1.setDrawCircleHole(false);
                set1.setCircleRadius(3f);
                set1.setCircleColor(Color.BLACK);

                // customize legend entry
                set1.setFormLineWidth(1f);
                set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
                set1.setFormSize(15.f);
                // text size of values
                set1.setValueTextSize(9f);
                // draw selection line as dashed
                set1.enableDashedHighlightLine(10f, 5f, 0f);
                // 设置显示曲线和X轴围成的区域阴影
                /*set1.setDrawFilled(true);
                set1.setFillFormatter(new IFillFormatter() {
                    @Override
                    public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                        return lineChart.getAxisLeft().getAxisMinimum();
                    }
                });*/

                // set color of filled area

                if (Utils.getSDKInt() >= 18) {
                    // drawables only supported on api level 18 and above
                    Drawable drawable = ContextCompat.getDrawable(this, R.drawable.fade_red);
                    set1.setFillDrawable(drawable);
                } else {
                    set1.setFillColor(Color.BLACK);
                }


                ArrayList<ILineDataSet> dataSets = new ArrayList<>();
                dataSets.add(set1); // add the data sets

                // create a data object with the data sets
                LineData data = new LineData(dataSets);
                // set data
                lineChart.setData(data);
                lineChart.invalidate();
            }

        }
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_second);
        ShujuxianshiShared = getSharedPreferences("share_shujusan", MODE_PRIVATE);
        mHelper = UserDBHelper.getInstance(this, 3);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        lineChart = (LineChart) findViewById(R.id.lineChaet);
        //ValueFormatter xAxisFormatter = new DayAxisValueFormatter(lineChart);
        //lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        //lineDataSet.setDrawFilled(true);
        {   // // Chart Style // //
            // background color
            lineChart.setBackgroundColor(Color.WHITE);
            // disable description text
            lineChart.getDescription().setEnabled(false);
            // enable touch gestures
            lineChart.setTouchEnabled(true);
            // set listeners
            //lineChart.setOnChartValueSelectedListener(true);
            //设置背景是否网格显示
            lineChart.setDrawGridBackground(false);
            // create marker to display box when values are selected
            //文本提示
           /* MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);
            *Set the marker to the chart
            *mv.setChartView(lineChart);
            lineChart.setMarker(mv);*/
            // 使图标可以缩放和拖拽
            lineChart.setDragEnabled(true);
            lineChart.setScaleEnabled(true);
            // 设置true支持两个指头向X、Y轴的缩放，如果为false，只能支持X或者Y轴的当方向缩放
            lineChart.setPinchZoom(true);
            lineChart.setScaleXEnabled(true);
            lineChart.setExtraTopOffset(10f);
        }
        YAxis yAxis;
        {   // // Y-Axis Style // //
            yAxis = lineChart.getAxisLeft();

            // disable dual axis (only use LEFT axis)
            lineChart.getAxisRight().setEnabled(false);

            // 启用网格线的虚线模式
            yAxis.setDrawGridLines(true);
            yAxis.enableGridDashedLine(10f, 10f, 0f);


            // axis range
            yAxis.setAxisMaximum(220f);
            yAxis.setAxisMinimum(0f);
        }
        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = lineChart.getXAxis();
            // 启用网格线的虚线模式
            xAxis.setDrawGridLines(true);
            xAxis.enableGridDashedLine(10f, 10f, 0f);
            xAxis.setGranularity(120f);

        }
        xAxis.setValueFormatter(new ValueFormatter() {
            private final SimpleDateFormat mFormat = new SimpleDateFormat("HH:mm", Locale.CHINA);
            @Override
            public String getFormattedValue(float value) {
                long millis = TimeUnit.MILLISECONDS.toMillis((long) value);
                return mFormat.format(new Date(millis));
            }
        });
        Legend l = lineChart.getLegend();
        // 设置图例样式
        l.setForm(Legend.LegendForm.LINE);
        test_xinlv = (TextView) findViewById(R.id.test_xinlv);
        test_xueyang = (TextView) findViewById(R.id.test_xueyang);
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        ShujuerShared = getSharedPreferences("share_shujuer", MODE_PRIVATE);
        float currentVolumeIndex = (float) audioManager.getStreamVolume(streamType);
        float maxVolumeIndex  = (float) audioManager.getStreamMaxVolume(streamType);
        this.volume = currentVolumeIndex / maxVolumeIndex;
        this.setVolumeControlStream(streamType);
        if (Build.VERSION.SDK_INT >= 21 ) {
            AudioAttributes audioAttrib = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_GAME)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build();
            SoundPool.Builder builder= new SoundPool.Builder();
            builder.setAudioAttributes(audioAttrib).setMaxStreams(MAX_STREAMS);
            this.soundPool = builder.build();
        }
        // for Android SDK < 21
        else {
            // SoundPool(int maxStreams, int streamType, int srcQuality)
            this.soundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);
        }

        // When Sound Pool load complete.
        this.soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                loaded = true;
            }
        });

        this.soundIdA = this.soundPool.load(this, R.raw.xindongguosu,1);
        this.soundIdB = this.soundPool.load(this,R.raw.xinlvguogao,1);
        this.soundIdC = this.soundPool.load(this,R.raw.xinlvguodi,1);
        this.soundIdD = this.soundPool.load(this,R.raw.dixueyang,1);
        this.soundIdE = this.soundPool.load(this,R.raw.xueyangbuzu,1);
        this.soundIdF = this.soundPool.load(this,R.raw.xueyanggao,1);


        mAppContext = getApplicationContext();

        Button buttonlanya = (Button) findViewById(R.id.buttonlanya);
        /*buttonlanya.setOnClickListener(v -> {
            Log.v("blueteeth", " click event");
            TabSecondActivity.this.onClick(v);
        });*/
        buttonlanya.setOnClickListener((v) -> {
            CustomPermissionUtil.request(getApplicationContext(), permission, callback);
        });
        mHandler.postDelayed(mImportService, 100);
    }

    public void playSoundA( )  {
        if(loaded)  {
            if(volume==0){
                float leftVolumn = 1f;
                float rightVolumn = 1f;
                int streamId = this.soundPool.play(this.soundIdA, leftVolumn, rightVolumn, 1, 0, 1f);
            }else {
                float leftVolumn = volume;
                float rightVolumn = volume;
                // Play sound of gunfire. Returns the ID of the new stream.
                int streamId = this.soundPool.play(this.soundIdA, leftVolumn, rightVolumn, 1, 0, 1f);
            }


        }
    }
    public void delay(int ms){
        try {
            Thread.currentThread();
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void playSoundB( )  {
        if(loaded) {
            if (volume == 0) {
                float leftVolumn = 1f;
                float rightVolumn = 1f;
                int streamId = this.soundPool.play(this.soundIdB, leftVolumn, rightVolumn, 1, 0, 1f);
            } else {
                float leftVolumn = volume;
                float rightVolumn = volume;
                // Play sound objects destroyed. Returns the ID of the new stream.
                int streamId = this.soundPool.play(this.soundIdB, leftVolumn, rightVolumn, 1, 0, 1f);
            }
        }
    }
    public void playSoundC( )  {
        if(loaded) {
            if (volume == 0) {
                float leftVolumn = 1f;
                float rightVolumn = 1f;
                int streamId = this.soundPool.play(this.soundIdC, leftVolumn, rightVolumn, 1, 0, 1f);
            } else {
                float leftVolumn = volume;
                float rightVolumn = volume;
                // Play sound objects destroyed. Returns the ID of the new stream.
                int streamId = this.soundPool.play(this.soundIdC, leftVolumn, rightVolumn, 1, 0, 1f);
            }
        }
    }
    public void playSoundD( )  {
        if(loaded) {
            if (volume == 0) {
                float leftVolumn = 1f;
                float rightVolumn = 1f;
                int streamId = this.soundPool.play(this.soundIdD, leftVolumn, rightVolumn, 1, 0, 1f);
            } else {
                float leftVolumn = volume;
                float rightVolumn = volume;
                // Play sound objects destroyed. Returns the ID of the new stream.
                int streamId = this.soundPool.play(this.soundIdD, leftVolumn, rightVolumn, 1, 0, 1f);
            }
        }
    }
    public void playSoundE( )  {
        if(loaded) {
            if (volume == 0) {
                float leftVolumn = 1f;
                float rightVolumn = 1f;
                int streamId = this.soundPool.play(this.soundIdE, leftVolumn, rightVolumn, 1, 0, 1f);
            } else {
                float leftVolumn = volume;
                float rightVolumn = volume;
                int streamId = this.soundPool.play(this.soundIdE, leftVolumn, rightVolumn, 1, 0, 1f);
            }
        }
    }
    public void playSoundF( )  {
        if(loaded) {
            if (volume == 0) {
                float leftVolumn = 1f;
                float rightVolumn = 1f;
                int streamId = this.soundPool.play(this.soundIdF, leftVolumn, rightVolumn, 1, 0, 1f);
            } else {
                float leftVolumn = volume;
                float rightVolumn = volume;
                int streamId = this.soundPool.play(this.soundIdF, leftVolumn, rightVolumn, 1, 0, 1f);
            }
        }
    }




   /* public void onClick(View v) {
        int targetRequestCode = R.id.buttonlanya % 4096;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android6.0之后使用蓝牙需要定位权限
            if (PermissionUtil.checkPermission(TabSecondActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION,
                    targetRequestCode)) {
                PermissionUtil.goActivity(TabSecondActivity.this, BluetoothActivity.class);
            }
        } else {
            PermissionUtil.goActivity(this, BluetoothActivity.class);
        }
    }*/

    private Handler mHandler = new Handler();
    private Runnable mImportService = new Runnable() {
        @Override
        public void run() {
            Intent intent = new Intent(TabSecondActivity.this, ImportDeviceService.class);
            startService(intent);
        }
    };


    static void toast(String message) {
        Toast.makeText(mAppContext, message, Toast.LENGTH_SHORT).show();
    }

    void log(String message) {
        Log.d(tag, message);
    }


}